package com.chuqiyun.authorization.controller.payment;

import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chuqiyun.authorization.annotation.ApiCheck;
import com.chuqiyun.authorization.entity.Alipay;
import com.chuqiyun.authorization.entity.Bill;
import com.chuqiyun.authorization.entity.Payment;
import com.chuqiyun.authorization.entity.User;
import com.chuqiyun.authorization.service.BillService;
import com.chuqiyun.authorization.service.PaymentService;
import com.chuqiyun.authorization.service.UserService;
import com.chuqiyun.authorization.utils.OrderUtil;
import com.chuqiyun.authorization.utils.ResponseResult;
import com.chuqiyun.authorization.utils.ServletUtil;
import com.chuqiyun.authorization.utils.exception.UnauthorizedException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mryunqi
 * @date 2023/4/22
 */
@RestController
@RequestMapping("/payment")
public class AliPayController {
    private static final String GATEWAY_URL = "https://openapi.alipay.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    /**
     * 签名方式
     */
    private static final String SIGN_TYPE = "RSA2";

    @Resource
    private PaymentService paymentService;

    @Resource
    private UserService userService;
    @Resource
    private BillService billService;
    @Value("${config.secret}")
    private String secret;

    @GetMapping("/AliPay") // &subject=xxx&out_trade_no=xxx&total_amount=xxx&body=xxx&type=0
    public String aliPay(Alipay aliPayDO, @RequestParam(value = "type",defaultValue = "0") int type, HttpServletRequest requestBody) throws UnauthorizedException {
        // 获取支付宝支付配置数据
        Payment aliPayConfig = paymentService.getAliPayConfig();
        // 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppid(),
                aliPayConfig.getPrivateKey(), FORMAT, CHARSET, aliPayConfig.getPublicKey(), SIGN_TYPE);

        // 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        // 给请求设置回调地址
        request.setNotifyUrl("http://"+requestBody.getServerName()+":"+requestBody.getServerPort()+"/payment/notify");

        request.setReturnUrl("http://"+requestBody.getServerName()+":"+requestBody.getServerPort()+"/payment/success");
        JSONObject bizContent = new JSONObject();

        Double totalAmount = aliPayDO.getTotal_amount();
        String traceNo;
        if (type ==0){
            traceNo = OrderUtil.generateOrderNo();
        }else {
            traceNo = aliPayDO.getOut_trade_no();
        }
        String subject = aliPayDO.getSubject();
        String body = aliPayDO.getBody();
        String productCode = aliPayDO.getProduct_code();

        User cookieUser = ServletUtil.getLoginMember(requestBody,secret);
        assert cookieUser != null;
        User user = userService.getUser(cookieUser.getPhone());
        billService.insertPayBill(user.getUuid(),traceNo,"AliPay",totalAmount,user.getCredit());

        // 我们自己生成的订单编号
        bizContent.put("out_trade_no", traceNo);
        // 订单的总金额
        bizContent.put("total_amount", totalAmount);
        // 支付的名称
        bizContent.put("subject", subject);
        // 支付描述
        bizContent.put("body",body);
        // 固定配置
        bizContent.put("product_code", productCode);
        request.setBizContent(bizContent.toJSONString());

        String result;
        // 调用SDK生成表单
        try {
            result = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            throw new UnauthorizedException();
        }
        return result;
    }

    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) throws UnauthorizedException, AlipayApiException {
        if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))){
            // 获取支付宝支付配置数据
            Payment aliPayConfig = paymentService.getAliPayConfig();

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                //System.out.println(name + " = " + request.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            // 验证签名
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getPublicKey(), "UTF-8");
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                Bill bill = billService.getBillByOrderId(params.get("out_trade_no"));
                bill.setOutOrderId(params.get("trade_no"));
                billService.updatePayBillSuccess(bill);
            }

        }
        return "success";
    }

    @GetMapping("/success")
    public ResponseResult<String> paySuccess(){
        return ResponseResult.ok("支付成功！");
    }
}
